<template>
    <div class="common-page page-officer-work-order" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/officer/work', '/officer/work/orders/type0', $route.fullPath]"></comp-paths>
            <div class="title" v-if="order">
                <div class="text">{{ order.title }}</div>
                <div class="flag" v-for="tag in order.tags" :key="tag.id">{{ tag.name }}</div>
            </div>
            <div class="title" v-else></div>
        </div>
        <div class="common-page__body common-form" style="display: flex" v-if="order">
            <div class="rows" style="flex: 3 1 0; padding-right: 0">
                <div class="row row--head">
                    <div class="name">基本信息</div>
                    <div class="value"></div>
                </div>
                <div class="row row--3x">
                    <div class="name">
                        <span v-if="order.company.type === 'company'">企业</span>
                        <span v-else-if="order.company.type === 'project'">项目</span>
                        <span v-else-if="order.company.type === 'area'">园区</span>
                        <span>名称</span>
                    </div>
                    <div class="value">{{ order.company.name }}</div>
                </div>
                <div class="row row--3x">
                    <div class="name">事项标题</div>
                    <div class="value">{{ order.title }}</div>
                </div>
                <div class="row row--3x">
                    <div class="name">事项描述</div>
                    <div class="value" style="white-space: pre-wrap">{{ order.content }}</div>
                </div>
                <div class="row row--3x">
                    <div class="name">事项附件</div>
                    <div class="value">
                        <div style="padding: 1px 0">
                            <comp-files-viewer :files="order.files" v-if="order.files.length > 0"></comp-files-viewer>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="name">事项分类</div>
                    <div class="value">
                        <span class="text" v-for="tag in order.tags" :key="tag.id">{{ tag.name }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">事项层面</div>
                  <div class="value">
                    <div v-if="order.level == 1 ">县级</div>
                    <div v-else-if="order.level == 2 ">市级</div>
                    <div v-else-if="order.level == 3 ">自治区级</div>
                    <div v-else>
                      <span v-if="order.dept.county.id">县级</span>
                      <span v-else-if="order.dept.city.id">市级</span>
                      <span v-else-if="order.dept.province.id">自治区级</span>
                    </div>
                  </div>
                </div>
                <div class="row">
                    <div class="name">事项状态</div>
                    <div class="value">
                        <span class="el-status--info" v-if="order.status === 'created'"></span>
                        <span class="el-status--danger" v-else-if="order.status === 'published' || order.status === 'return'"></span>
                        <span class="el-status--warning" v-else-if="order.status === 'handling'"></span>
                        <span class="el-status--success" v-else-if="order.status === 'finished'"></span>
                        <span>{{ order.statusText }}</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="name">提交人</div>
                    <div class="value">
                        <span>{{ order.creator.name }}</span>
                        <span style="margin-left: 0.5em; color: #aaa">{{ order.creator.number }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">提交时间</div>
                    <div class="value">{{ order.createdAt }}</div>
                </div>
<!--                <div class="row row&#45;&#45;2x">-->
<!--                    <div class="name">负责工作队</div>-->
<!--                    <div class="value">-->
<!--                        <span>{{ order.hand.name }}</span>-->
<!--                    </div>-->
<!--                </div>-->
<!--                <div class="row">-->
<!--                    <div class="name">负责服务专员</div>-->
<!--                    <div class="value">-->
<!--                        <span>{{ order.handler.name }}</span>-->
<!--                        <span style="margin-left: 0.5em; color: #aaa">{{ order.handler.number }}</span>-->
<!--                    </div>-->
<!--                </div>-->
                <div class="row row--2x">
                    <div class="name">关注数量</div>
                    <div class="value">
                        <span class="text">{{ order.likes }}人</span>
                        <span class="button" @click="getOrderLikers()">查看</span>
                        <span class="button" @click="addOrderLiker()" v-if="order.liked">取消关注</span>
                        <span class="button" @click="addOrderLiker()" v-else>关注</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">办结时间</div>
                    <div class="value">
                        <span>{{ order.finishedAt }}</span>
                    </div>
                </div>
                <div class="row row--2x">
                    <div class="name">评价人</div>
                    <div class="value">
                        <span>{{ order.evaluatedCreator.name }}</span>
                        <span style="margin-left: 0.5em; color: #aaa">{{ order.evaluatedCreator.number }}</span>
                    </div>
                </div>
                <div class="row">
                    <div class="name">评价打分</div>
                    <div class="value">
                        <span v-if="order.evaluated === 'yes'">{{ order.evaluatedStars }}分</span>
                    </div>
                </div>
                <div class="row row--3x">
                    <div class="name">评价内容</div>
                    <div class="value">
                        <span v-if="order.evaluated === 'yes'">{{ order.evaluatedContent }}</span>
                    </div>
                </div>
            </div>
            <div class="rows" style="flex: 2 1 0; flex-wrap: nowrap; flex-direction: column; padding-right: 0">
                <div class="row row--head">
                    <div class="name">处理过程信息</div>
                    <div class="value"></div>
                </div>
                <div class="row row--3x" style="flex: 1 1 0; overflow-x: hidden; overflow-y: auto">
                    <div class="value">
                        <comp-order-tracks :order="order"></comp-order-tracks>
                    </div>
                </div>
            </div>
        </div>
        <div class="common-page__foot">
            <el-button type="primary" size="small" icon="el-icon-check" @click="replyOrderTrackSign()" v-if="editing">答复</el-button>
            <el-button type="primary" size="small" icon="el-icon-check" @click="zaicidafufun()" v-if="editing2">再次答复</el-button>
<!--            <el-button type="plain" size="small" icon="el-icon-close" @click="returnOrderTrackSign()">退回</el-button>-->
          <el-button type="plain" size="small" icon="el-icon-close" @click="revokeOrderTrack()" v-if="revoking">撤回</el-button>
        </div>
        <comp-dialog title="查看关注" width="60vw" height="80vh" ref="orderLiker">
            <comp-order-likers style="height: 100%" ref="orderLikerList" :orderId="orderId">
                <template #foot="scope">
                    <el-button type="plain" size="small" icon="el-icon-close" @click="getOrderLikers('end')">关闭</el-button>
                </template>
            </comp-order-likers>
        </comp-dialog>
        <comp-dialog title="事项答复" ref="orderTrackSignReplyForm">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="order && track && sign">
                <el-form-item label="答复意见：">
                    <el-input type="textarea" v-model="sign.replyContent" style="width: 480px" placeholder="请输入" :maxlength="1000" :rows="5" resize="none" :readonly="loading" @change="replyOrderTrackSign('validate')"></el-input>
                </el-form-item>
                <el-form-item label="答复附件：">
                    <div style="width: 480px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in sign.replyFiles" :key="index" disable-transitions closable @close="replyOrderTrack('sign-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="replyOrderTrackSign('sign-file-upload', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="replyOrderTrackSign('sign-file-upload', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="replyOrderTrackSign('submit')">确定</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="replyOrderTrackSign('end')">取消</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="再次答复" ref="zaiorderTrackSignReplyForm">
            <el-form size="small" label-width="98px" style="margin-right: 20px">
                <el-form-item label="答复意见：">
                    <el-input type="textarea" v-model="zaireplyContent" style="width: 480px" placeholder="请输入" :maxlength="1000" :rows="5" resize="none" :readonly="loading" @change="replyOrderTrackSign('validate')"></el-input>
                </el-form-item>
                <el-form-item label="答复附件：">
                    <div style="width: 480px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in zaireplyFiles" :key="index" disable-transitions closable @close="zaiflie('sign-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="zaiflie('zaiflile', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="zaiflie('zaiflile', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="zaiflie('sumbmit')">确定</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="zaiflie('end')">取消</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="事项退回" ref="orderTrackSignReturnForm">
            <el-form size="small" label-width="98px" style="margin-right: 20px" @submit.native.prevent v-if="order && track && sign">
                <el-form-item label="退回意见：">
                    <el-input type="textarea" v-model="sign.replyContent" style="width: 480px" placeholder="请输入" :maxlength="1000" :rows="5" resize="none" :readonly="loading" @change="returnOrderTrackSign('validate')"></el-input>
                </el-form-item>
                <el-form-item label="退回附件：">
                    <div style="width: 480px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in sign.replyFiles" :key="index" disable-transitions closable @close="replyOrderTrack('sign-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="returnOrderTrackSign('sign-file-upload', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="returnOrderTrackSign('sign-file-upload', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="returnOrderTrackSign('submit')">确定</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="returnOrderTrackSign('end')">取消</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, selectFile, cache } from "../util";
    export default {
        name: "page-officer-work-order",
        title: "事项详情",
        nodes: ["/menu/officer-work"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            orderId: "",
            order: null,
            track: null,
            sign: null,
            editing: false,
            editing2: false,
            revoking:false,
            zaireplyContent:"",
            zaireplyFiles:[],
            flowld:null,
        }),
        methods: {
            addOrderLiker() {
                if (this.loading) return;
                let order = this.order;
                this.loading = true;
                this.plugins.user.addOrderLiker(order).then((res) => {
                    this.loading = false;
                    if (res.code === 0) {
                        this.plugins.modal.toast("操作成功！", "success");
                        this.init();
                    } else {
                        this.plugins.modal.toast("操作失败<br>" + res.code + "：" + res.msg, "error");
                    }
                });
            },
            getOrderLikers(action, data) {
                if (this.loading) return;
                if (!action || action === "start") {
                    this.$refs.orderLiker.init();
                    this.$nextTick(() => this.$refs.orderLikerList.init());
                } else if (action === "end") {
                    this.$refs.orderLiker.close();
                }
            },
          revokeOrderTrack() {
            if (this.loading) return;
            if (!this.revoking) return;
            let order = this.order;
            this.plugins.modal.alert("撤回确认", "确定撤回吗？", "warning", ["确定撤回", "再想想"]).then((ok) => {
              if (!ok) return;
              this.loading = true;
              this.plugins.user.revokeOrderTrackGov(order, order.tracks[0]).then((res) => {
                this.loading = false;
                if (res.code === 0) {
                  this.plugins.modal.toast("操作成功！", "success");
                  this.init();
                } else {
                  this.plugins.modal.alert("操作失败", res.code + "：" + res.msg, "error");
                }
              });
            });
          },
            uploadFile(type, file, callback) {
                if (this.loading) return;
                if (type && file) {
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    this.loading = true;
                    this.plugins.user.uploadFile(file, type, progress).then((res) => {
                        this.loading = false;
                        if (res.code === 0) string(() => callback(res.data));
                        else this.plugins.modal.alert("上传失败", res.code + "：" + res.msg, "error");
                    });
                } else if (type === "image") {
                    selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else this.uploadFile(type, file, callback);
                    });
                } else if (type === "document") {
                    selectFile(".xls,.xlsx,.doc,.docx,.pdf").then((file) => {
                        if (file.size > 10 * 1048576) this.plugins.modal.toast("文档过大，不能大于10MB哦！请重新选择。", "error");
                        else this.uploadFile(type, file, callback);
                    });
                }
            },
            zaicidafufun(){
                    this.$refs.zaiorderTrackSignReplyForm.init();

            },
            zaiflie(action,data){
                if(action==="sign-file-delete"){
                    let file = data;
                    let index = this.zaireplyFiles.indexOf(file);
                    if (index > -1) this.zaireplyFiles.splice(index, 1);
                }else if(action === "zaiflile"){
                    let type = data;
                    if (type) this.uploadFile(type, null, (file) => {
                        this.zaireplyFiles.push(file);
                        this.replyOrderTrackSign("validate");
                    });
                }else if(action === "sumbmit"){
                    this.loading = true;
                    let relayform = {}
                    relayform.id = this.flowld;
                    relayform.content = this.zaireplyContent,
                    relayform.files = this.zaireplyFiles,
                    console.log(relayform);
                    this.plugins.user.zaidafu(relayform).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("操作成功！", "success");
                           this.flowld = null,
                           this.zaireplyContent = null,
                           this.zaireplyFiles  = []
                            this.$refs.zaiorderTrackSignReplyForm.close();

                            this.init();
                        } else {
                            this.plugins.modal.toast("操作失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                }

            },

            replyOrderTrackSign(action, data) {
                if (this.loading) return;
                let profile = this.profile;
                let order = this.order;
                let track = this.track;
                let sign = this.sign;
                if (!action || action === "start") {
                    this.track = order.tracks[0];
                    this.sign = order.tracks[0].signs.find((sign) => sign.handler.id === profile.id);
                    this.replyOrderTrackSign("validate");
                    this.$refs.orderTrackSignReplyForm.init();
                }
                else if (action === "validate") {
                    let error = "";
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "sign-file-upload") {
                    console.log(1111);
                    let type = data;
                    if (type) this.uploadFile(type, null, (file) => {
                        sign.replyFiles.push(file);
                        this.replyOrderTrackSign("validate");
                    });
                }else if(action ==="zaiflile"){
                    console.log(123);
                }
                else if (action === "sign-file-delete") {
                    let file = data;
                    let index = sign.replyFiles.indexOf(file);
                    if (index > -1) sign.replyFiles.splice(index, 1);
                } else if (action === "submit") {
                    if (!this.replyOrderTrackSign("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.replyOrderTrackSign(order, track, sign).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("操作成功！", "success");
                            this.replyOrderTrackSign("end");
                            this.init();
                        } else {
                            this.plugins.modal.toast("操作失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.orderTrackSignReplyForm.close();
                }
            },
            returnOrderTrackSign(action, data) {
                if (this.loading) return;
                let profile = this.profile;
                let order = this.order;
                let track = this.track;
                let sign = this.sign;
                if (!action || action === "start") {
                    this.track = order.tracks[0];
                    this.sign = order.tracks[0].signs.find((sign) => sign.finished === "not" && sign.handler.id === profile.id);
                    this.returnOrderTrackSign("validate");
                    this.$refs.orderTrackSignReturnForm.init();
                } else if (action === "validate") {
                    let error = "";
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "sign-file-upload") {
                    let type = data;
                    if (type) this.uploadFile(type, null, (file) => {
                        sign.replyFiles.push(file);
                        this.returnOrderTrackSign("validate");
                    });
                } else if (action === "sign-file-delete") {
                    let file = data;
                    let index = sign.replyFiles.indexOf(file);
                    if (index > -1) sign.replyFiles.splice(index, 1);
                } else if (action === "submit") {
                    if (!this.returnOrderTrackSign("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.returnOrderTrackSign(order, track, sign).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("操作成功！", "success");
                            this.returnOrderTrackSign("end");
                            this.init();
                        } else {
                            this.plugins.modal.toast("操作失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.orderTrackSignReturnForm.close();
                }
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                let query = this.$route.query;
                let order = null;
                this.loading = true;
                this.orderId = query.orderId;
                this.order = cache(query.orderId);
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }, async () => {
                    let res = await this.plugins.user.getOrder(query.orderId);
                    if (res.code === 0) order = res.data;
                    if (res.code === 0) {
                        for (let track of order.tracks) {
                            let handler = track.handler;
                            let depments = handler.depments.splice(0);
                            for (let depment of depments) depment.dept.id === track.dept.id && handler.depments.push(depment);
                            let creator = order.creator;
                            let matched = track.type === "start" && track.handler.id === creator.id && creator.role === "holder";
                            if (matched) order.creator = track.handler;
                        }
                        for (let creator of [order.creator, order.evaluatedCreator]) {
                            let employees = creator.employees.splice(0);
                            for (let employee of employees) employee.company.id === order.company.id && creator.employees.push(employee);
                        }
                    }
                    return res;
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.order = cache(query.orderId, order);
                        console.log(this.order);
                        console.log(this.order.tracks[0].type);
                        let len = this.order.tracks.length
                        // if(this.order.tracks[len-1].type==='relay'){
                        //     this.flowld = this.order.tracks[len-1].id;
                        //     console.log(this.flowld);
                        // }else if(this.order.tracks[len-1].type==='finish'){
                        //     this.flowld = this.order.tracks[len-2].id;
                        //
                        // }
                        if(this.order.tracks[0].type==='finish'){
                          this.flowld = this.order.tracks[1].id;
                         }else {
                          this.flowld = this.order.tracks[0].id;
                        }
                        console.log(this.flowld);
                        this.editing = order.status === "handling" && order.tracks[0].type === "relay" && order.tracks[0].finished === "not"
                            && (order.tracks[0].signs.some((sign) => sign.handler.id === this.profile.id && (sign.type === "created" || sign.type === "revoke"))
                                && !order.tracks[0].signs.some((sign) => sign.handler.id === this.profile.id && sign.type === "reply")) && this.profile.role === "officer";
                        if(this.order.tracks[0].type === "finish"){
                          this.editing2 =  this.profile.role === "officer" && !this.editing &&
                              order.tracks[1].signs.some((sign) => sign.handler.id === this.profile.id);
                        }else{
                          this.editing2 =  this.profile.role === "officer" && !this.editing &&
                              order.tracks[0].signs.some((sign) => sign.handler.id === this.profile.id);
                        }
                        if(order.tracks.length > 1){
                          this.revoking = order.status === "handling" && order.tracks[0].finished === "not" && (order.tracks[0].signs.some((sign) => sign.handler.id === this.profile.id
                              && sign.type === "reply") || (order.tracks[0].signs.length == 0 && order.tracks[1].signs.some((sign) => sign.handler.id === this.profile.id && sign.type === "reply"))  ) && this.profile.role === "officer";
                        }else{
                          this.revoking = order.status === "handling" && order.tracks[0].finished === "not" && (order.tracks[0].signs.some((sign) => sign.handler.id === this.profile.id
                              && sign.type === "reply")) && this.profile.role === "officer";
                        }
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/officer/work/orders/type1"));
                    }
                });
            },

        },
    };
</script>

<style lang="scss">
    .page-officer-work-order {
        overflow: hidden;
    }
</style>
